package com.qiangesoft.security.config;

import com.qiangesoft.security.access.CustomAccessDeniedHandler;
import com.qiangesoft.security.filter.CaptchaFilter;
import com.qiangesoft.security.filter.TokenFilter;
import com.qiangesoft.security.handler.CustomAuthenticationFailHandler;
import com.qiangesoft.security.handler.CustomAuthenticationSuccessHandler;
import com.qiangesoft.security.handler.CustomLogoutSuccessHandler;
import com.qiangesoft.security.point.CustomAuthenticationEntryPoint;
import com.qiangesoft.security.service.CustomUserDetailsService;
import com.qiangesoft.security.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * 配置类
 *
 * @author qiangesoft
 * @date 2024-05-14
 */
@EnableWebSecurity
// 开启方法级安全验证
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;

    @Autowired
    private CustomAuthenticationFailHandler customAuthenticationFailHandler;

    @Autowired
    private CustomLogoutSuccessHandler customLogoutSuccessHandler;

    @Autowired
    private CustomAccessDeniedHandler customAccessDeniedHandler;

    @Autowired
    private CustomAuthenticationEntryPoint customAuthenticationEntryPoint;

    @Autowired
    private CaptchaFilter captchaFilter;

    @Autowired
    private JwtUtil jwtUtil;

    @Bean
    protected UserDetailsService userDetailsService() {
        return new CustomUserDetailsService();
    }

    @Bean
    public TokenFilter tokenFilter() throws Exception {
        return new TokenFilter(authenticationManager(), userDetailsService(), jwtUtil);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .userDetailsService(userDetailsService())
                .passwordEncoder(passwordEncoder());
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                // 禁用csrf
                .csrf().disable()
                // 禁用session
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)

                // 接口授权
                .and()
                .authorizeRequests()
                .antMatchers(
                        HttpMethod.GET,
                        "/",
                        "/captcha",
                        "/static/**",
                        "/templates/**",
                        "/favicon.ico"
                ).permitAll()
                .antMatchers(HttpMethod.POST, "/login").permitAll()
                .anyRequest().authenticated()

                // 登录逻辑
                .and()
                .formLogin()
                .successHandler(customAuthenticationSuccessHandler)
                .failureHandler(customAuthenticationFailHandler)

                // 退出逻辑
                .and()
                .logout()
                .logoutSuccessHandler(customLogoutSuccessHandler)

                // 验证账号密码之前执行
                .and()
                .addFilterBefore(captchaFilter, TokenFilter.class)
                .addFilterBefore(tokenFilter(), UsernamePasswordAuthenticationFilter.class)

                // 异常处理器
                .exceptionHandling()
                .authenticationEntryPoint(customAuthenticationEntryPoint)
                .accessDeniedHandler(customAccessDeniedHandler)

                // 禁用缓存
                .and()
                .headers().cacheControl();
    }

}
